/**
 * 
 */
package com.dhcc.cdbp.query;

import static org.junit.Assert.*;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author 谢进军
 *
 */
public class QueryParserTest {
	private static final String directoryPath = "src/main/resources/lucenedir";
	private static final String fieldName = "contents";
	private static final String queryString = "i服了u";
	@Before public void setUp() throws Exception {
	}
	@Test public void test() throws IOException, ParseException {
		Directory dic = FSDirectory.open(Paths.get(directoryPath));
		IndexReader reader = DirectoryReader.open(dic);
		IndexSearcher searcher = new IndexSearcher(reader);
		
		QueryParser parser = new QueryParser(fieldName,new StandardAnalyzer());
		Query query = parser.parse(fieldName + ":" + queryString);
		
		TopDocs docs = searcher.search(query, 10);
		ScoreDoc[] hits = docs.scoreDocs;
		for (int i = 0; i < hits.length; i++) {
			int docID = hits[i].doc;
			Document document = searcher.doc(docID);
			System.out.println("=================");
			System.out.println(document.get(fieldName));
		}
		assertEquals(2, docs.totalHits);
	}
	@After public void tearDown() throws Exception {
	}
}
